package com.rou.im.framework.core.processorstack.processor;

import com.rou.im.framework.core.Request;
import com.rou.im.framework.core.context.RequestContextHolder;
import com.rou.im.framework.core.exception.CommonRuntimeException;
import com.rou.im.framework.core.exception.UnrecognizedRuntimeException;
import com.rou.im.framework.core.processorstack.Processor;
import com.rou.im.framework.core.processorstack.StackInvocation;

/**
 * <p></p>
 *
 * @author GaoShuangWen
 * @since 2020-05-13 22:31
 */

public class ExceptionProcessor implements Processor {

    /**
     * 抛出异常标志
     */
    private boolean isThrowException = true;

    @Override
    public void process(Request request, StackInvocation invocation) {
         try {
             invocation.invoke(request);
         }catch (Exception e){
             CommonRuntimeException exception ;
             if(e instanceof CommonRuntimeException ){
                 exception = (CommonRuntimeException) e;
             }else {
                 exception = new UnrecognizedRuntimeException("X11");
             }
             // 将异常放入上下文中
             RequestContextHolder.getContext().setException(exception);

             if(isThrowException()){
               throw exception;
             }
         }
    }
    public boolean isThrowException() {
        return isThrowException;
    }

    public void setThrowException(boolean throwException) {
        isThrowException = throwException;
    }
}
